﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

public class MultiThread
{
    private List<Thread> threadList = new List<Thread>();
    private ArrayList stringList;
    private event EventHandler OnNumberClear;//数据删除完成引发的事件

    public static int ThreadNum = 6;

    public static bool ThreadAbort = false;

    public static void MultiThreadStart()
    {
        MultiThread threadTask = new MultiThread(ThreadNum);
        threadTask.Action();
    }

    public MultiThread(int number)
    {
        for (int i = 0; i < number; i++)
        {
            Thread thread = new Thread(new ThreadStart(Run));//多个线程共同做一件事情
            thread.Name = String.Format("线程{0}", i);
            threadList.Add(thread);
        }
        OnNumberClear += new EventHandler(ThreadDemo_OnNumberClear);
    }

    /// <summary>
    /// 开始工作
    /// </summary>
    public void Action()
    {
        foreach (var v in threadList)
        {
            v.Start();
        }
    }

    /// <summary>
    /// 共同做的工作
    /// </summary>
    private void Run()
    {
        while (true)
        {
            Monitor.Enter(this);//锁定，保持同步
            if (stringList.Count == 0)
            {
                OnNumberClear(this, new EventArgs());//引发完成事件
            }
            Monitor.Exit(this);//取消锁定
            Thread.Sleep(5);
        }
    }

    //执行完成之后，停止所有线程
    public void ThreadDemo_OnNumberClear(object sender, EventArgs e)
    {
        Console.WriteLine("执行完了，停止了所有线程的执行。");
        foreach (var v in threadList)
        {
            v.Abort();
        }
    }
}